var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var indexRouter = require("./routes/index");
var platformRouter = require("./routes/platform/index");
var commonRouter = require('./routes/upload')
var app = express();
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
// 允许跨域
app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type,Content-Length, Authorization, Accept,X-Requested-With"
  );
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("X-Powered-By", " 3.2.1");
  if (req.method === "OPTIONS") res.send(200); /*让options请求快速返回*/
  else next();
});

// 解析 token 的中间件
const expressjwt = require("express-jwt");
const {secretKey} = require("./config/jwtConfig");
// 使用 .unless({ path: [/^\/api\//] }) 指定哪些接口不需要进行 Token 的身份认证
app.use(
  expressjwt({ secret: secretKey, algorithms: ['HS256'] }).unless({ path: ["/platform/login"] })
);
// 中间件解析body参数
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
/**
 * 验证token是否过期redis
 */
const redisMiddleware = require('./utils/redisMiddleware')
app.use(redisMiddleware)
app.use("/", indexRouter);
app.use("/platform", platformRouter);
app.use('/common', commonRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  console.log(req.url)
  // 捕获身份认证失败的错误
  if (err.name === "UnauthorizedError"){
    return res.status(401).json({
      msg: "请登录",
    });
  }
  
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
